package cn.yoaket.util;

import cn.yoaket.exception.ContextException;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


/**
 * @author Alex
 */
public class BeanGenerate {

    private BeanGenerate(){

    }
    public static Object generate(BeanDefinition def) throws ContextException {
        Class<?> c;
        Constructor<?> con;
        Object obj;
        try{
           c =  Class.forName(def.className);
            con = c.getConstructor();
            obj = con.newInstance();
        }catch (Exception e){
            throw new ContextException(ContextException.Type.INSTANCE_ERROR);
        }
        //生成get方法实现name的注入
        var fieldMap = def.getFields();
        for (String field :fieldMap.keySet()){
            String methodName = "set" + field.substring(0,1).toUpperCase() + field.substring(1);
            try {
                Class<?> type = c.getDeclaredField(field).getType();
                Method method = c.getDeclaredMethod(methodName,type);
                method.invoke(obj,fieldMap.get(field));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return  obj;
    }
}


